import time
from typing import Literal

import jwt

from DataModels.share import RespInfo, StatusInfo, RespResultCode, TokenPayload
from config import SECRET, logger
from .share import timestamp


def generate_token(paylaod: TokenPayload):
    token = jwt.encode(
        payload={
            "phone": paylaod.phone,
            "createTime": paylaod.createTime,
        },
        key=SECRET,
        algorithm="HS256",
    )
    return token


def decode_token(token: str):
    decode_data = jwt.decode(
        token,
        key=SECRET,
        algorithms=["HS256"],
    )

    return TokenPayload(**decode_data)


def check_token(
    token: str, check_none: bool = True
) -> tuple[Literal[False], RespInfo] | tuple[Literal[True], TokenPayload]:
    if check_none:
        # 如果确定token为None时存在意义，则不需要检查
        # 此处检查会破坏意义
        if (token is None) or (token == "") or (token == "null"):
            return False, RespInfo(
                status=StatusInfo(
                    code=RespResultCode.TokenEmpty,
                    msg="当前未登录",
                )
            )

    try:
        payload = decode_token(token)
        phone = payload.phone
        create_time = payload.createTime
    except Exception as e:
        logger.error(e)
        return False, RespInfo(
            status=StatusInfo(
                code=RespResultCode.DataCorrupted,
                msg="当前未登录",
            )
        )

    if (phone is None) or (create_time is None) or (phone == ""):
        return False, RespInfo(
            status=StatusInfo(
                code=RespResultCode.ExtractPhoneErr,
                msg="当前未登录",
            )
        )

    now = int(time.time())
    if now - create_time > 60 * 60 * 24 * 7:
        return False, RespInfo(
            status=StatusInfo(
                code=RespResultCode.TokenExpire,
                msg="登录过期，请重新登录",
            )
        )

    return (True, TokenPayload(phone=phone, createTime=timestamp()))
